package cn.kgc.spring.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: mosin
 * @version: v1.0  2022/10/12
 * 自定义类型转换器
 * 1.编写类实现 Converter<S, T> 接口 S -> T  Converter<String, Date> 实现convert方法
 * 2.将自定义的转换器声明在spring的配置文件中
 * 3.将自定义转换器注册到ConversionServiceFactoryBean中  id 必须是conversionService
 */
public class MyDateConverter implements Converter<String, Date> {

    private String pattern;

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public Date convert(String source) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        try {
            Date date = simpleDateFormat.parse(source);
            return  date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
